package net.htjs.juc.chapter06.myatomicinteger;

import net.htjs.juc.chapter06.accountcas.Account;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class TestMyAtomicInteger {

    public static void main(String[] args) {
        MyAtomicInteger myAtomicInteger = new MyAtomicInteger(10000);
        Account.demo(myAtomicInteger);
    }
}

class MyAtomicInteger implements Account {
    private volatile int value;
    private static long valueOffset;
    private static Unsafe UNSAFE;
    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            UNSAFE = (Unsafe) field.get(null);
            valueOffset = UNSAFE.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public int getValue() {
         return value;
    }

    public void decrement(int amount) {
        while (true) {
            int prev = this.value;
            int next = prev - amount;
            if (UNSAFE.compareAndSwapInt(this, valueOffset, prev, next)) {
                break;
            }
        }
    }


    public MyAtomicInteger(int value) {
        this.value = value;
    }

    @Override
    public Integer getBalance() {
        return getValue();
    }

    @Override
    public void withdraw(Integer amount) {
        decrement(amount);
    }
}

